package com.aco.party.web.controller.client;

import com.aco.party.enums.*;
import com.aco.party.model.po.*;
import com.aco.party.model.vo.*;
import com.aco.party.model.vo.common.PageParam;
import com.aco.party.model.vo.common.Response;
import com.aco.party.model.vo.common.UserWithRoleVo;
import com.aco.party.service.system.*;
import com.aco.party.util.ConfigResource;
import com.aco.party.util.CookieUtil;
import com.aco.party.util.HTMLUtil;
import com.aco.party.util.NavUtils;
import com.aco.party.web.command.system.EditPostsCommand;
import com.aco.party.web.command.system.EditQuestionCommand;
import com.aco.party.web.controller.system.BaseController;
import com.aco.party.web.validator.system.EditSimpleInputValidator;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;
import java.util.logging.Logger;

@Controller
public class CommonController extends BaseController {
    private Logger logger = Logger.getLogger(getClass().getName());

    @Resource
    private DictService dictService;

    @Resource
    private MetaService metaService;

    @Resource
    private ProductService productService;

    @Resource
    private PeopleService peopleService;

    @Resource
    private CompanyService companyService;

    @Resource
    private UserService userService;

    @Resource
    private HireService hireService;

    @Resource
    private PostsService postsService;

    @Resource
    private QuestionService questionService;

    @Resource
    private EventService eventService;

    @Resource
    private MessageService messageService;

    @Resource
    private TermsService termsService;

    @Resource
    private VisitService visitService;

    @Resource
    private LinksService linksService;

    @Resource
    private CommentsService commentsService;

    private EditSimpleInputValidator validator = new EditSimpleInputValidator();

    private final Integer MAXPREVIEWLENGTH = 100;

    private final Integer MINPREVIEWLENGTH = 50;


    @RequestMapping(value = { "/home"})
    public String home(HttpServletResponse response,HttpServletRequest request,Model model,PostsParam param) {
        model.addAttribute("home_banner_img_1", metaService.getByName("home_banner_img_1").getType());
        model.addAttribute("home_banner_img_2", metaService.getByName("home_banner_img_2").getType());
        model.addAttribute("home_banner_img_3", metaService.getByName("home_banner_img_3").getType());
        model.addAttribute("home_banner_img_4", metaService.getByName("home_banner_img_4").getType());
        model.addAttribute("home_banner_url_1", metaService.getByName("home_banner_url_1").getType());
        model.addAttribute("home_banner_url_2", metaService.getByName("home_banner_url_2").getType());
        model.addAttribute("home_banner_url_3", metaService.getByName("home_banner_url_3").getType());
        model.addAttribute("home_banner_url_4", metaService.getByName("home_banner_url_4").getType());
        model.addAttribute("home_banner_title_1", metaService.getByName("home_banner_title_1").getType());
        model.addAttribute("home_banner_title_2", metaService.getByName("home_banner_title_2").getType());
        model.addAttribute("home_banner_title_3", metaService.getByName("home_banner_title_3").getType());
        model.addAttribute("home_banner_title_4", metaService.getByName("home_banner_title_4").getType());

        param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
        param.setType(PostTypeEnum.普通.getValue());
        List<PostsVo> postsVos = postsService.getByPage(new PageParam((param.getPage() - 1) * param.getSize(), param.getSize()), param);
        if (postsVos != null) {
            for (PostsVo vo : postsVos) {
                if (vo.getPostContent() != null && vo.getPostContent().length() > 0) {
                    vo.setPostContent(HTMLUtil.delHTMLTag(vo.getPostContent()));
                    if (vo.getPostContent().length() > MINPREVIEWLENGTH) {
                        vo.setPostContent(vo.getPostContent().substring(0, MINPREVIEWLENGTH) + "...");
                    }
                }
            }
        }
        int total = postsService.getTotal(param);
        model.addAttribute("vos", postsVos);
        model.addAttribute("pages", NavUtils.build(param.getPage(), param.getSize(), total, request.getRequestURI() + "?page="));
        LinksParam linksParam = new LinksParam();
        linksParam.setLinkVisible("Y");
        linksParam.setType("合作伙伴");
        List<Links> fs = linksService.getByPage(null, linksParam);
        if(fs != null && fs.size() > 0)
            model.addAttribute("fs", fs);

        LinksParam linksParam2 = new LinksParam();
        linksParam2.setLinkVisible("Y");
        linksParam2.setType("友情链接");
        List<Links> fl = linksService.getByPage(null,linksParam2);
        if(fl != null && fl.size() > 0)
            model.addAttribute("fl", fl);

        HireParam hireParam = new HireParam();
        hireParam.setOrder("views");
        List<HireVo> hotHires = hireService.getByPage(new PageParam(0,5), hireParam);
        model.addAttribute("hotHires", hotHires);
        model.addAttribute("thisWeekWork", hireService.getThisWeekNewWork());
        model.addAttribute("ad_url", metaService.getByName("ad_banner_url_1").getType());
        model.addAttribute("ad_img",metaService.getByName("ad_banner_img_1").getType());

        ProductParam productParam = new ProductParam();
        productParam.setStatus(DataBaseEnum.显示.getValue());
        List<ProductVo> vos = productService.getByPage(new PageParam(0, 5), productParam);
        if (vos != null)
            model.addAttribute("products", vos);
        model.addAttribute("latests", getLatestQuestion(3));
        return "client/index";
    }


    @RequestMapping("/home/postsList")
    @ResponseBody
    public Response getHomePostsList(HttpServletResponse resp,PostsParam param){
        Response response = new Response();
        param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
        param.setType(PostTypeEnum.普通.getValue());
        List<PostsVo> postsVos = postsService.getByPage(new PageParam((param.getPage() - 1) * param.getSize(),param.getSize()), param);
        if (postsVos != null) {
            for (PostsVo vo : postsVos) {
                if (vo.getPostContent() != null && vo.getPostContent().length() > 0) {
                    vo.setPostContent(HTMLUtil.delHTMLTag(vo.getPostContent()));
                    if (vo.getPostContent().length() > MINPREVIEWLENGTH) {
                        vo.setPostContent(vo.getPostContent().substring(0, MINPREVIEWLENGTH) + "...");
                    }
                }
            }
        }
        int total = postsService.getTotal(param);
        Map data = new HashMap();
        data.put("list", postsVos);
        data.put("total", total);
        response.setData(data);
        return response;
    }

    @RequestMapping("/getDakaRandom")
    @ResponseBody
    public Response getDakaRandom(HttpServletResponse resp,Integer page){
        Response response = new Response();
        PostsParam param = new PostsParam();
        param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
        param.setType(PostTypeEnum.普通.getValue());
        param.setCat(termsService.getBySlug("interview").getId());
        List<PostsVo> postsVos = postsService.getByPage(new PageParam((page - 1) * param.getSize(), 5), param);
        Map data = new HashMap();
        data.put("list", postsVos);
        response.setData(data);
        return response;
    }

    @RequestMapping("/posts/list/{slug}")
    public String postsList(HttpServletResponse response,HttpServletRequest request,Model model,@PathVariable("slug")String slug,PostsParam param){
        Terms terms = termsService.getBySlug(slug);
        if(terms != null){
            model.addAttribute("catName",terms.getName());
            param.setCat(terms.getId());
            param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
            param.setType(PostTypeEnum.普通.getValue());
            param.setUp(2);
            List<PostsVo> postsVos = postsService.getByPage(new PageParam((param.getPage() - 1) * param.getSize(), param.getSize()),param);
            if (postsVos != null) {
                for (PostsVo vo : postsVos) {
                    if (vo.getPostContent() != null && vo.getPostContent().length() > 0) {
                        vo.setPostContent(HTMLUtil.delHTMLTag(vo.getPostContent()));
                        if (vo.getPostContent().length() > MINPREVIEWLENGTH) {
                            vo.setPostContent(vo.getPostContent().substring(0, MINPREVIEWLENGTH) + "...");
                        }
                    }
                }
            }
            int total = postsService.getTotal(param);
            model.addAttribute("vos",postsVos);
            model.addAttribute("pages", NavUtils.build(param.getPage(), param.getSize(), total, request.getRequestURI() + "?page="));
            //获取文章列表页顶部top 2
            param = new PostsParam();
            param.setType(PostTypeEnum.普通.getValue());
            param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
            param.setCat(terms.getId());
            param.setUp(1);
            param.setLimit(2);
            List<PostsVo> top2 = postsService.getByPage(null, param);
            if(CollectionUtils.isEmpty(top2) || top2.size() < 2){
                param.setUp(null);
                param.setOrderClause(" extra_3*1 desc ");
                top2 = postsService.getByPage(null, param);
            }
            model.addAttribute("top2",top2);

            param = new PostsParam();
            param.setType(PostTypeEnum.普通.getValue());
            param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
            param.setCat(terms.getId());
            param.setOrderClause(" extra_3*1 desc ");
            param.setLimit(5);
            model.addAttribute("vs",postsService.getByPage(null,param));
        }
        String catClass;
        String textColor;
        if("case".equals(slug)){
            catClass = "anli";
            textColor = "rel1";
        }else if("interview".equals(slug)){
            catClass = "duihua";
            textColor = "rel4";
        }else if("personnel".equals(slug)){
            catClass = "renshi";
            textColor = "rel3";
        }else if("special-column".equals(slug)){
            catClass = "zhuanti";
            textColor = "rel2";
        }else{
            catClass = "zixun";
            textColor = "rel0";
        }
        model.addAttribute("catClass", catClass);
        model.addAttribute("textColor", textColor);

        model.addAttribute("ad_url",metaService.getByName("ad_banner_url_1").getType());
        model.addAttribute("ad_img",metaService.getByName("ad_banner_img_1").getType());
        return "client/posts_list";
    }

    @RequestMapping("/posts/{id}")
    public String postDetail(HttpServletResponse response,Model model,HttpServletRequest request,@PathVariable("id")Long id){
        PostsVo vo = postsService.getVoById(id);
        PostsParam param = new PostsParam();
        if(vo != null) {
            addVisit(id, VisitTypeEnum.文章.getValue(), request.getRemoteAddr());
            if (vo.getExtra3() == null) {
                vo.setExtra3("1");
            } else {
                vo.setExtra3(Integer.parseInt(vo.getExtra3()) + 1 + "");
            }
            PostsVo temp = new PostsVo();
            temp.setId(vo.getId());
            temp.setExtra3(vo.getExtra3());
            postsService.update(temp);
            model.addAttribute("vo", vo);
            if(PostsStatusEnum.显示.getValue().equals(vo.getPostStatus())) {
                param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
                param.setType(PostTypeEnum.普通.getValue());
                param.setCat(vo.getPostTerm());
                List<Long> ids = postsService.getIdsByParam(param);
                int idx = 0;
                if (ids != null) {
                    for (int i = 0; i < ids.size(); i++) {
                        if (ids.get(i).intValue() == vo.getId()) {
                            idx = i;
                        }
                    }
                    if (idx == ids.size() - 1) {
                        //没有下一个
                    } else {
                        model.addAttribute("next", postsService.getVoById(ids.get(idx + 1)));
                    }
                }
            }

            String cookie = CookieUtil.getCookie(request, "bigfa_ding_" + id);
            if (!StringUtils.isEmpty(cookie)) {
                model.addAttribute("done", "done");
            }

            //推荐产品
            if (!StringUtils.isEmpty(vo.getTags())) {
                ProductParam productParam = new ProductParam();
                productParam.setTitle(vo.getTags());
                List<ProductVo> productVos = productService.getByPage(new PageParam(0, 1), productParam);
                if(productVos != null && productVos.size() > 0)
                    model.addAttribute("rp",productVos.get(0));
            }

            //评论
            CommentsParam commentsParam = new CommentsParam();
            commentsParam.setPostIds(Arrays.asList(id));
            commentsParam.setCommentApproved(1);
            List<CommentsVo> commentsVos = commentsService.getByPage(null,commentsParam);
            if(commentsVos != null && commentsVos.size() > 0){
                model.addAttribute("cvs",commentsVos);
            }
        }

        param = new PostsParam();
        param.setType(PostTypeEnum.普通.getValue());
        param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
        param.setCat(vo.getPostTerm());
        param.setOrderClause(" extra_3*1 desc ");
        param.setLimit(5);
        model.addAttribute("vs", postsService.getByPage(null, param));

        model.addAttribute("ad_url", metaService.getByName("ad_banner_url_1").getType());
        model.addAttribute("ad_img", metaService.getByName("ad_banner_img_1").getType());
        model.addAttribute("post_thum_img",vo.getPostImg());
        return "client/posts_detail";
    }

    @RequestMapping("/posts/up")
    @ResponseBody
    public Response upPost(HttpServletResponse response,Long id){
        Posts p = postsService.getVoById(id);
        int num = 0;
        Posts temp = new Posts();
        if(p != null){
            if(!StringUtils.isEmpty(p.getGuid())){
                num = Integer.parseInt(p.getGuid());
            }
            temp.setId(p.getId());temp.setGuid((num+1) + "");
            postsService.update(temp);
        }
        CookieUtil.addCookie(response, "bigfa_ding_" + id, num + 1 + "");
        Response res = new Response();
        res.setData(num + 1);
        return res;
    }

    @RequestMapping("/client/success")
    public String success() {
        return "client/success";
    }

    @RequestMapping(value = {"/baike/index"})
    public String baikeIndex(HttpServletRequest request,HttpServletResponse response,Model model,Integer page) {
        return baikeIndex(request,model, 0,page);
    }

    @RequestMapping(value = {"/baike/cat/{cat}"})
    public String baikeIndex(HttpServletRequest request,Model model, @PathVariable("cat") Integer cat,Integer page) {
        DictParam param = new DictParam();
        param.setCat(cat);
        if(page == null || page == 0) page = 1;
        List<DictVo> dictVos = dictService.getByPage(new PageParam((page - 1) * 10, 10), param);
        if (dictVos != null) {
            for (DictVo vo : dictVos) {
                if (vo.getContent() != null && vo.getContent().length() > 0) {
                    vo.setContent(HTMLUtil.delHTMLTag(vo.getContent()));
                    if (vo.getContent().length() > 100) {
                        vo.setContent(vo.getContent().substring(0, 100) + "...");
                    }
                }
            }
            model.addAttribute("bakes", dictVos);
        }
        Integer totalSize = dictService.getTotal(param);
        List<Meta> metas = metaService.getByType(MetaTypeEnum.词条类目.getValue());
        if (metas != null) {
            model.addAttribute("cats", metas);
            model.addAttribute("pages", NavUtils.build(page, 10, totalSize, request.getRequestURI() + "?page="));
        }

        model.addAttribute("activityCat", cat);
        return "client/baike";
    }

    @RequestMapping(value = {"/baike/{id}"})
    public String baikeDetail(HttpServletRequest request, Model model, @PathVariable("id")Long id) {
        DictParam param = new DictParam();
        param.setId(id);
        List<DictVo> dictVos = dictService.getByPage(null, param);
        if (dictVos != null && dictVos.size() > 0) {
            model.addAttribute("bake", dictVos.get(0));
            model.addAttribute("activityCat", dictVos.get(0).getCat());
            addVisit(id, VisitTypeEnum.百科.getValue(), request.getRemoteAddr());
        }
        List<Meta> metas = metaService.getByType(MetaTypeEnum.词条类目.getValue());
        if (metas != null)
            model.addAttribute("cats", metas);
        String cookie = CookieUtil.getCookie(request,"bigfa_ding_baike_" + id);
        if(!StringUtils.isEmpty(cookie)){
            model.addAttribute("done","done");
        }
        return "client/baike_detail";
    }

    @RequestMapping("/baike/up")
    @ResponseBody
    public Response upBaike(HttpServletRequest request,HttpServletResponse response,Long id){
        addVisit(id, VisitTypeEnum.百科点赞.getValue(), request.getRemoteAddr());
        DictParam param = new DictParam();
        param.setId(id);
        List<DictVo> dictVos = dictService.getByPage(null, param);
        int num = 0;
        if (dictVos != null && dictVos.size() > 0) {
            num += dictVos.get(0).getLikes();
        }
        CookieUtil.addCookie(response,"bigfa_ding_baike_" + id,num+"");
        Response res = new Response();
        res.setData(num);
        return res;
    }

    /**
     * ================================产品
     **/

    @RequestMapping(value = {"/product/index"})
    public String productIndex(HttpServletRequest request,Model model,DataBaseFilterVo filterVo) {
        ProductParam param = new ProductParam();
        param.setStatus(DataBaseEnum.显示.getValue());
        if(filterVo != null){
            if(filterVo.getType() != null && filterVo.getType() != 0){
                param.setType(filterVo.getType());
            }
            if (filterVo.getPlatform() != null) {
                param.setPlatform(filterVo.getPlatform());
                param.setPlatform1("%_" + filterVo.getPlatform() + "_%");
                param.setPlatform2(filterVo.getPlatform() + "_%");
                param.setPlatform3("%_" + filterVo.getPlatform());
            }
            if(!StringUtils.isEmpty(filterVo.getOrder())){
                param.setOrder(filterVo.getOrder());
            }else{
                //默认排序按照浏览量
                param.setOrder("views");
            }
        }
        filterVo.setSize(12);
        int totalSize = productService.getTotal(param);
        List<ProductVo> vos = productService.getByPage(new PageParam((filterVo.getPage() - 1) * filterVo.getSize(),filterVo.getSize()), param);
        model.addAttribute("products", vos);
        model.addAttribute("size", totalSize);
        model.addAttribute("pages", NavUtils.build(filterVo.getPage(), filterVo.getSize(), totalSize, request.getRequestURI() + "?page="));

        List<FilterVo> typeUrls = new ArrayList<>();
        List<Meta> metas = new ArrayList<>();
        metas.add(new Meta(0L, "不限"));
        metas.addAll(metaService.getByType(MetaTypeEnum.产品类型.getValue()));
        for (Meta meta : metas){
            FilterUrlVo filterUrlVo = getUrl(filterVo,"type=" + meta.getId()+"");
            if((filterVo.getType() == null || filterVo.getType() == 0L) && meta.getId() == 0L){
                filterUrlVo.setIsactivity(1);
            }
            typeUrls.add(new FilterVo(meta.getId()+"",meta.getName(),filterUrlVo.getUrl(),filterUrlVo.getIsactivity()));
        }

        List<FilterVo> platformUrls = new ArrayList<>();
        metas = new ArrayList<>();
        metas.add(new Meta(0L,"不限"));
        metas.addAll(metaService.getByType(MetaTypeEnum.平台类型.getValue()));
        for (Meta meta : metas){
            FilterUrlVo filterUrlVo = getUrl(filterVo,"platform=" + meta.getId()+"");
            if((filterVo.getPlatform() == null || filterVo.getPlatform() == 0L) && meta.getId() == 0L){
                filterUrlVo.setIsactivity(1);
            }
            platformUrls.add(new FilterVo(meta.getId()+"",meta.getName(),filterUrlVo.getUrl(),filterUrlVo.getIsactivity()));
        }

        //排序方式 ：浏览最多 ,更新时间
        List<FilterVo> timeUrls = new ArrayList<>();
        FilterUrlVo viewsVo = getUrl(filterVo,"order=views");
        if(filterVo.getOrder() == null || "views".equals(filterVo.getOrder())){
            viewsVo.setIsactivity(1);
        }
        timeUrls.add(new FilterVo("views", "浏览最多", viewsVo.getUrl(), viewsVo.getIsactivity()));
        FilterUrlVo updateTimeVo = getUrl(filterVo,"order=update_time");
        timeUrls.add(new FilterVo("update_time", "最近更新", updateTimeVo.getUrl(), updateTimeVo.getIsactivity()));

        model.addAttribute("typeUrls",typeUrls);
        model.addAttribute("platformUrls",platformUrls);
        model.addAttribute("timeUrls",timeUrls);
        return "client/product_list";
    }

    @RequestMapping(value = {"/product/id/{id}"})
    public String productDetail(HttpServletRequest request, Model model, @PathVariable("id") Long id) {
        ProductVo vo = productService.getVoById(id);
        model.addAttribute("product", vo);
        addVisit(id, VisitTypeEnum.产品.getValue(), request.getRemoteAddr());
        ProductParam param = new ProductParam();
        param.setOrder("views");
        param.setStatus(DataBaseEnum.显示.getValue());
        List<ProductVo> vos = productService.getByPage(new PageParam(0, 5), param);
        if (vos != null)
            model.addAttribute("products", vos);
        //没有登录
        if(getCurrentUser().getId() == -1){
            model.addAttribute("no_login",1);
        }
        return "client/product_detail";
    }

    @RequestMapping(value = {"/product/batchRefresh"})
    @ResponseBody
    public Response productBatchRefresh(HttpServletRequest request, Model model) {
        Response response = new Response();
        PageParam pageParam = new PageParam(0, 5);
        ProductParam param = new ProductParam();
        param.setStatus(DataBaseEnum.显示.getValue());
        List<ProductVo> vos = productService.getByPage(pageParam, param);
        response.setData(vos);
        return response;
    }

    /**
     * ================================大咖
     **/

    @RequestMapping(value = {"/people/index"})
    public String peopleIndex(HttpServletRequest request, Model model, DataBaseFilterVo filterVo) {
        PeopleParam param = new PeopleParam();
        param.setStatus(DataBaseEnum.显示.getValue());
        if(filterVo != null){
            if(filterVo.getType() != null && filterVo.getType() != 0){
                param.setType(filterVo.getType());
            }
            if(!StringUtils.isEmpty(filterVo.getCity()) && !"不限".equals(filterVo.getCity())){
                param.setCity("%" + filterVo.getCity() + "%");
            }
            if(!StringUtils.isEmpty(filterVo.getOrder())){
                param.setOrder(filterVo.getOrder());
            }else{
                param.setOrder("views");
            }
        }
        filterVo.setSize(12);
        int totalSize = peopleService.getTotal(param);
        List<PeopleVo> vos = peopleService.getByPage(new PageParam((filterVo.getPage() - 1) * filterVo.getSize(),filterVo.getSize()), param);
        model.addAttribute("peoples", vos);
        model.addAttribute("size", totalSize);
        model.addAttribute("pages", NavUtils.build(filterVo.getPage(), filterVo.getSize(), totalSize, request.getRequestURI() + "?page="));

        List<FilterVo> typeUrls = new ArrayList<>();
        List<Meta> metas = new ArrayList<>();
        metas.add(new Meta(0L,"不限"));
        metas.addAll(metaService.getByType(MetaTypeEnum.大咖类型.getValue()));
        for (Meta meta : metas){
            FilterUrlVo filterUrlVo = getUrl(filterVo,"type=" + meta.getId()+"");
            if((filterVo.getType() == null || filterVo.getType() == 0L) && meta.getId() == 0L){
                filterUrlVo.setIsactivity(1);
            }
            typeUrls.add(new FilterVo(meta.getId()+"",meta.getName(),filterUrlVo.getUrl(),filterUrlVo.getIsactivity()));
        }

        List<FilterVo> areaUrls = new ArrayList<>();
        List<String> areas = Arrays.asList("不限","上海","北京","广州");
        for (String area : areas){
            FilterUrlVo filterUrlVo = getUrl(filterVo,"city=" + area+"");
            if((filterVo.getCity() == null || "不限".equals(filterVo.getCity())) && area.equals("不限")){
                filterUrlVo.setIsactivity(1);
            }
            areaUrls.add(new FilterVo(area, area, filterUrlVo.getUrl(), filterUrlVo.getIsactivity()));
        }

        //排序方式 ：浏览最多 ,更新时间
        List<FilterVo> timeUrls = new ArrayList<>();
        FilterUrlVo viewsVo = getUrl(filterVo,"order=views");
        if(filterVo.getOrder() == null || "views".equals(filterVo.getOrder())){
            viewsVo.setIsactivity(1);
        }
        timeUrls.add(new FilterVo("views", "浏览最多", viewsVo.getUrl(), viewsVo.getIsactivity()));
        FilterUrlVo updateTimeVo = getUrl(filterVo,"order=update_time");
        timeUrls.add(new FilterVo("update_time","最近更新",updateTimeVo.getUrl(),updateTimeVo.getIsactivity()));

        model.addAttribute("typeUrls",typeUrls);
        model.addAttribute("areaUrls",areaUrls);
        model.addAttribute("timeUrls",timeUrls);

        return "client/people_list";
    }

    @RequestMapping(value = {"/people/id/{id}"})
    public String peopleDetail(HttpServletRequest request, Model model, @PathVariable("id") Long id) {
        PeopleVo vo = peopleService.getVoById(id);
        model.addAttribute("people", vo);
        addVisit(id, VisitTypeEnum.大咖.getValue(), request.getRemoteAddr());

        PeopleParam peopleParam = new PeopleParam();
        peopleParam.setStatus(DataBaseEnum.显示.getValue());
        peopleParam.setOrder("views");
        List<PeopleVo> hotPeoples = peopleService.getByPage(new PageParam(0,5),peopleParam);
        if(hotPeoples != null && hotPeoples.size() > 0){
            model.addAttribute("peoples",hotPeoples);
        }

        PostsParam postsParam = new PostsParam();
        postsParam.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
        postsParam.setCat(172L);
        postsParam.setType(PostTypeEnum.普通.getValue());
        postsParam.setKeywords("%" + vo.getName() + "%");
        List<PostsVo> vos = postsService.getByPage(new PageParam(0,1),postsParam);
        if(vos != null && vos.size() > 0)
            model.addAttribute("vo", vos.get(0));
        return "client/people_detail";
    }

    /**
     * ================================公司
     **/

    @RequestMapping(value = {"/company/index"})
    public String companyIndex(HttpServletRequest request,Model model,DataBaseFilterVo filterVo) {
        CompanyParam param = new CompanyParam();
        param.setStatus(DataBaseEnum.显示.getValue());
        if(filterVo != null){
            if(filterVo.getType() != null && filterVo.getType() != 0){
                param.setType(filterVo.getType());
            }
            if(!StringUtils.isEmpty(filterVo.getCity()) && !"不限".equals(filterVo.getCity())){
                param.setCity("%" + filterVo.getCity() + "%");
            }
            if(!StringUtils.isEmpty(filterVo.getOrder())){
                param.setOrder(filterVo.getOrder());
            }else{
                //默认排序按照浏览量
                param.setOrder("views");
            }
            filterVo.setSize(6);
        }
        int totalSize = companyService.getTotal(param);
        List<CompanyVo> vos = companyService.getByPage(new PageParam((filterVo.getPage() - 1) * filterVo.getSize(), filterVo.getSize()), param);
        model.addAttribute("companys", vos);
        model.addAttribute("size", totalSize);
        model.addAttribute("pages", NavUtils.build(filterVo.getPage(), filterVo.getSize(), totalSize, request.getRequestURI() + "?page="));

        List<FilterVo> typeUrls = new ArrayList<>();
        List<Meta> metas = new ArrayList<>();
        metas.add(new Meta(0L,"不限"));
        metas.addAll(metaService.getByType(MetaTypeEnum.公司类型.getValue()));
        for (Meta meta : metas){
            FilterUrlVo filterUrlVo = getUrl(filterVo,"type=" + meta.getId()+"");
            if((filterVo.getType() == null || filterVo.getType() == 0L) && meta.getId() == 0L){
                filterUrlVo.setIsactivity(1);
            }
            typeUrls.add(new FilterVo(meta.getId()+"",meta.getName(),filterUrlVo.getUrl(),filterUrlVo.getIsactivity()));
        }

        List<FilterVo> areaUrls = new ArrayList<>();
        List<String> areas = Arrays.asList("不限","上海","北京","广州");
        for (String area : areas){
            FilterUrlVo filterUrlVo = getUrl(filterVo,"city=" + area+"");
            if((filterVo.getCity() == null || "不限".equals(filterVo.getCity())) && area.equals("不限")){
                filterUrlVo.setIsactivity(1);
            }
            areaUrls.add(new FilterVo(area, area, filterUrlVo.getUrl(), filterUrlVo.getIsactivity()));
        }

        //排序方式 ：浏览最多 ,更新时间
        List<FilterVo> timeUrls = new ArrayList<>();
        FilterUrlVo viewsVo = getUrl(filterVo,"order=views");
        if(filterVo.getOrder() == null || "views".equals(filterVo.getOrder())){
            viewsVo.setIsactivity(1);
        }
        timeUrls.add(new FilterVo("views", "浏览最多", viewsVo.getUrl(), viewsVo.getIsactivity()));
        FilterUrlVo updateTimeVo = getUrl(filterVo,"order=update_time");
        timeUrls.add(new FilterVo("update_time","最近更新",updateTimeVo.getUrl(),updateTimeVo.getIsactivity()));

        model.addAttribute("typeUrls",typeUrls);
        model.addAttribute("areaUrls",areaUrls);
        model.addAttribute("timeUrls",timeUrls);
        return "client/company_list";
    }

    @RequestMapping(value = {"/company/id/{id}"})
    public String companyDetail(HttpServletRequest request, Model model, @PathVariable("id") Long id) {
        CompanyVo vo = companyService.getVoById(id);
        model.addAttribute("company", vo);
        addVisit(id, VisitTypeEnum.公司.getValue(), request.getRemoteAddr());

        CompanyParam param = new CompanyParam();
        param.setStatus(DataBaseEnum.显示.getValue());
        List<CompanyVo> vos = companyService.getByPage(new PageParam(0, 5), param);
        model.addAttribute("companys", vos);
        //没有登录
        if(getCurrentUser().getId() == -1){
            model.addAttribute("no_login",1);
        }
        return "client/company_detail";
    }

    @Data
    private class FilterUrlVo {
        private int isactivity = 0;

        private String url;

        @Override
        public String toString() {
            return "FilterUrlVo{" +
                    "isactivity=" + isactivity +
                    ", url='" + url + '\'' +
                    '}';
        }
    }

    /**
     * 根据传入参数拼接出访问Url
     * @param filterVo 各种过滤条件
     * @param currentFilter 格式： type=1
     * @return
     */
    private FilterUrlVo getUrl(DataBaseFilterVo filterVo, String currentFilter) {
        FilterUrlVo filterUrlVo = new FilterUrlVo();
        StringBuilder baseUrl = new StringBuilder();
        if (filterVo != null) {
            String[] filterPairs;
            if (currentFilter != null) {
                filterPairs = currentFilter.split("=");
                PropertyDescriptor[] props = null;
                try {
                    props = Introspector.getBeanInfo(filterVo.getClass(), Object.class)
                            .getPropertyDescriptors();
                    if (props != null) {
                        for (int i = 0; i < props.length; i++) {
                            String name = props[i].getName();
                            Method readMethod = props[i].getReadMethod();
                            Object obj = readMethod.invoke(filterVo);
                            if (name.equals(filterPairs[0])) {
                                //当前条件与已存在的互斥
                                if (obj != null) {
                                    if (obj.toString().equals(filterPairs[1])) {
                                        //相同 则激活
                                        filterUrlVo.setIsactivity(1);
                                    }
                                }
                                baseUrl.append("&" + currentFilter);
                            } else {
                                //不互斥可以追加
                                if (obj != null) {
                                    baseUrl.append("&" + name + "=" + obj);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        filterUrlVo.setUrl(baseUrl.toString());
        return filterUrlVo;
    }

    /**
     * 个人中心
     **/
    @RequestMapping(value = {"/profile"})
    public String profile(HttpServletResponse response,Model model,Long userId) {
        User user = null;
        if(userId == null) {
            model.addAttribute("can_edit","1");
            user = getCurrentUser();
        }else{
            user = userService.getUser(userId);
        }
        model.addAttribute("user", user);
        PostsParam postsParam = new PostsParam();
        postsParam.setType(PostTypeEnum.魔客.getValue());
        postsParam.setAuthorId(user.getId());
        List<PostsVo> postsVos = postsService.getByPage(null, postsParam);
        for (PostsVo vo : postsVos) {
            if (vo.getPostContent() != null && vo.getPostContent().length() > 0) {
                vo.setPostContent(HTMLUtil.delHTMLTag(vo.getPostContent()));
                if (vo.getPostContent().length() > 100) {
                    vo.setPostContent(vo.getPostContent().substring(0, 100) + "...");
                }
            }
        }
        model.addAttribute("posts", postsVos);

        QuestionParam questionParam = new QuestionParam();
        questionParam.setUserId(user.getId());
        List<QuestionVo> qs = questionService.getByPage(null, questionParam);
        model.addAttribute("qs", qs);

        MessageParam messageParam = new MessageParam();
        messageParam.setTarget(user.getId());
        List<MessageVo> ms = messageService.getByPage(null, messageParam);
        if(ms != null){
            for (MessageVo vo : ms){
                if(vo.getStatus() == 0) {
                    Message temp = new Message();
                    temp.setId(vo.getId());
                    temp.setStatus(1);
                    messageService.update(temp);
                }
            }
        }
        model.addAttribute("ms", ms);

        UserWithRoleVo vo = userService.getUserWithRole(user.getId());
        if(vo.getRoleId() == 3 || vo.getRoleId() == 4 || vo.getRoleId() == 5){
            model.addAttribute("canPub",1);
        }

        return "client/profile";
    }

    /**
     * 招聘
     **/
    @RequestMapping(value = {"/hire/index"})
    public String hireIndex(Model model) {
        return hireCityName(model, "");
    }

    @RequestMapping(value = {"/hire/city/{name}"})
    public String hireCityName(Model model, @PathVariable("name") String cityName) {
        HireParam param = new HireParam();
        if (!StringUtils.isEmpty(cityName)) {
            param.setCityName("%" + cityName + "%");
        }
        List<HireVo> vos = hireService.getByPage(null, param);
        if (vos != null) {
            for (HireVo vo : vos) {
                if (vo.getAboutUs() != null && vo.getAboutUs().length() > 0) {
                    vo.setAboutUs(HTMLUtil.delHTMLTag(vo.getAboutUs()));
                    if (vo.getAboutUs().length() > 100) {
                        vo.setAboutUs(vo.getAboutUs().substring(0, 100) + "...");
                    }
                }
            }
        }
        model.addAttribute("hires", vos);
        model.addAttribute("thisWeekWork",hireService.getThisWeekNewWork());
        param = new HireParam();
        param.setOrder("views");
        List<HireVo> hotHires = hireService.getByPage(new PageParam(0,5), param);

        model.addAttribute("hotHires", hotHires);
        return "client/hire_list";
    }

    @RequestMapping(value = {"/hire/{id}"})
    public String hireIndex(HttpServletRequest request,Model model, @PathVariable("id") String id) {
        if (NumberUtils.isNumber(id)) {
            HireVo hire = hireService.getVoById(Long.parseLong(id));
            addVisit(Long.parseLong(id), VisitTypeEnum.招聘.getValue(), request.getRemoteAddr());
            model.addAttribute("hire", hire);
        }
        HireParam hireParam = new HireParam();
        hireParam.setOrder("views");
        List<HireVo> hotHires = hireService.getByPage(new PageParam(0,5), hireParam);
        model.addAttribute("hotHires", hotHires);
        model.addAttribute("thisWeekWork",hireService.getThisWeekNewWork());
        //没有登录
        if(getCurrentUser().getId() == -1){
            model.addAttribute("no_login",1);
        }
        return "client/hire_detail";
    }

    /**
     * 魔客专栏
     **/
    @RequestMapping(value = {"/moke/index"})
    public String mokeIndex(Model model) {
        UserQueryParam param = new UserQueryParam();
        //热门魔客
        param.setRoleId(3);
        param.setAudit(0);//同意0
        param.setIsHot(1);
        List<UserListResponse> hotAuthors = userService.getAuthorsByParam(new PageParam(0, 6), param);

        //最新魔客
        param = new UserQueryParam();
        param.setAudit(0);//同意0
        param.setRoleId(3);
        List<UserListResponse> latestAuthors = userService.getAuthorsByParam(new PageParam(0, 6), param);

        //作者文章
        PostsParam postsParam = new PostsParam();
        postsParam.setType("moke");
        postsParam.setStatuses(new ArrayList<>(Arrays.asList(PostsStatusEnum.审核通过.getValue())));
        List<PostsVo> articles = postsService.getByPage(null, postsParam);
        if (articles != null) {
            for (PostsVo vo : articles) {
                if (vo.getPostContent() != null && vo.getPostContent().length() > 0) {
                    vo.setPostContent(HTMLUtil.delHTMLTag(vo.getPostContent()));
                    if (vo.getPostContent().length() > 100) {
                        vo.setPostContent(vo.getPostContent().substring(0, 100) + "...");
                    }
                }
            }
        }

        model.addAttribute("hotAuthors", hotAuthors);
        model.addAttribute("latestAuthors", latestAuthors);
        model.addAttribute("articles", articles);
        return "client/moke_list";
    }

    @RequestMapping(value = "/moke/apply", method = RequestMethod.POST)
    @ResponseBody
    public Response applyMoke() {
        Response response = new Response();
        User moke = getCurrentUser();
        if (moke.getId() == -1L) {
            //没有登录
            response.setStatus(-1);
        } else {
            User user = new User();
            user.setId(moke.getId());
            user.setExtra2(1);//申请中
            userService.updateUser(user);
        }
        return response;
    }

    @RequestMapping(value = {"/moke/posts/{id}"})
    public String getAuthorPosts(HttpServletRequest request,Model model, @PathVariable("id") Long id) {
        PostsVo vo = postsService.getVoById(id);
        PostsParam postsParam = new PostsParam();
        if(vo != null) {
            addVisit(id, VisitTypeEnum.魔客文章.getValue(), request.getRemoteAddr());

            model.addAttribute("vo", vo);

            User user = userService.getUser(vo.getPostAuthor());
            model.addAttribute("u", user);

            if (vo.getExtra3() == null) {
                vo.setExtra3("1");
            } else {
                vo.setExtra3(Integer.parseInt(vo.getExtra3()) + 1 + "");
            }
            PostsVo temp = new PostsVo();
            temp.setId(vo.getId());
            temp.setExtra3(vo.getExtra3());
            postsService.update(temp);

            String cookie = CookieUtil.getCookie(request, "bigfa_ding_" + id);
            if (!StringUtils.isEmpty(cookie)) {
                model.addAttribute("done", "done");
            }

            postsParam.setAuthorId(user.getId());
            postsParam.setStatuses(new ArrayList<>(Collections.singleton(PostsStatusEnum.审核通过.getValue())));
            postsParam.setType(PostTypeEnum.魔客.getValue());
            Integer total = postsService.getTotal(postsParam);
            model.addAttribute("t", total);

            //作者文章评论数
            postsParam = new PostsParam();
            postsParam.setAuthorId(user.getId());
            postsParam.setStatuses(new ArrayList<>(Collections.singleton(PostsStatusEnum.审核通过.getValue())));
            postsParam.setType(PostTypeEnum.魔客.getValue());
            List<PostsVo> postsVos = postsService.getByPage(null,postsParam);
            if(postsVos != null && postsVos.size() > 0) {
                List<Long> voIds = new ArrayList<>();
                for (PostsVo v : postsVos){
                    voIds.add(v.getId());
                }
                if(voIds.size() > 0){
                    CommentsParam commentsParam = new CommentsParam();
                    commentsParam.setPostIds(voIds);
                    commentsParam.setCommentApproved(1);
                    Integer cTotal = commentsService.getTotal(commentsParam);
                    model.addAttribute("ct",cTotal);
                }

            }

            //评论
            CommentsParam commentsParam = new CommentsParam();
            commentsParam.setPostIds(Arrays.asList(id));
            commentsParam.setCommentApproved(1);
            List<CommentsVo> commentsVos = commentsService.getByPage(null,commentsParam);
            if(commentsVos != null && commentsVos.size() > 0){
                model.addAttribute("cvs",commentsVos);
            }
        }

        postsParam = new PostsParam();
        postsParam.setStatuses(new ArrayList<>(Collections.singleton(PostsStatusEnum.审核通过.getValue())));
        postsParam.setType(PostTypeEnum.魔客.getValue());
        List<PostsVo> ps = postsService.getByPage(new PageParam(0, 5), postsParam);
        model.addAttribute("ps", ps);

        return "client/moke_posts_detail";
    }

    @RequestMapping(value = {"/moke/user/{id}"})
     public String getMokeUser(Model model, @PathVariable("id") Long id) {
        User user = userService.getUser(id);
        if(user != null) {
            PostsParam param = new PostsParam();
            param.setType(PostTypeEnum.魔客.getValue());
            param.setStatuses(Arrays.asList(PostsStatusEnum.审核通过.getValue()));
            param.setAuthorId(id);
            Integer count = postsService.getTotal(param);
            List<PostsVo> postsVos = postsService.getByPage(null, param);
            if (postsVos != null) {
                for (PostsVo vo : postsVos) {
                    if (vo.getPostContent() != null && vo.getPostContent().length() > 0) {
                        vo.setPostContent(HTMLUtil.delHTMLTag(vo.getPostContent()));
                        if (vo.getPostContent().length() > 100) {
                            vo.setPostContent(vo.getPostContent().substring(0, 100) + "...");
                        }
                    }
                }
            }
            model.addAttribute("user", user);
            model.addAttribute("count", count);
            model.addAttribute("ps", postsVos);

            //作者文章评论数
            PostsParam postsParam = new PostsParam();
            postsParam.setAuthorId(user.getId());
            postsParam.setStatuses(new ArrayList<>(Collections.singleton(PostsStatusEnum.审核通过.getValue())));
            postsParam.setType(PostTypeEnum.魔客.getValue());
            List<PostsVo> postsMokeVos = postsService.getByPage(null,postsParam);
            if(postsMokeVos != null && postsMokeVos.size() > 0) {
                List<Long> voIds = new ArrayList<>();
                for (PostsVo v : postsMokeVos){
                    voIds.add(v.getId());
                }
                if(voIds.size() > 0){
                    CommentsParam commentsParam = new CommentsParam();
                    commentsParam.setPostIds(voIds);
                    commentsParam.setCommentApproved(1);
                    Integer cTotal = commentsService.getTotal(commentsParam);
                    model.addAttribute("ct",cTotal);
                }

            }
        }
        return "client/moke_user";
    }

    /**
     * 问答
     **/
    @RequestMapping(value = {"/question/index"})
    public String questionIndex(Model model) {
        QuestionParam param = new QuestionParam();
        param.setPId(0L);
        param.setStatuses(new ArrayList<>(Arrays.asList(QuestionStatusEnum.推荐.getDesc())));
        List<QuestionVo> ups = questionService.getByPage(null, param);

        model.addAttribute("ups", ups);
        model.addAttribute("latests", getLatestQuestion(5));
        return "client/wenda_list";
    }

    @RequestMapping(value = {"/question/detail/{id}"})
    public String questionDetail(Model model, @PathVariable("id") String id) {
        if (NumberUtils.isNumber(id)) {
            QuestionVo vo = questionService.getVoById(Long.parseLong(id));
            model.addAttribute("q", vo);

            QuestionParam param = new QuestionParam();
            param.setPId(Long.parseLong(id));
            List<QuestionVo> answers = questionService.getByPage(null, param);
            model.addAttribute("answers", answers);
        }

        model.addAttribute("latests", getLatestQuestion(5));

        return "client/wenda_detail";
    }

    private List<QuestionVo> getLatestQuestion(Integer size) {
        QuestionParam param = new QuestionParam();
        param.setPId(0L);
        param.setStatuses(new ArrayList<>(Arrays.asList(QuestionStatusEnum.推荐.getDesc(), QuestionStatusEnum.显示.getDesc())));
        PageParam pageParam = null;
        if(size != null){
            pageParam = new PageParam(0,size);
        }
        List<QuestionVo> latests = questionService.getByPage(pageParam, param);
        return latests;
    }

    @RequestMapping(value = "/question/add", method = RequestMethod.GET)
    public String questionAdd(@ModelAttribute EditQuestionCommand command) {
        return "client/wenda_input";
    }

    @RequestMapping(value = "/question/add", method = RequestMethod.POST)
    public String questionAdd(Model model, @ModelAttribute EditQuestionCommand command, BindingResult errors, RedirectAttributes attributes) {
        validator.validate(command, errors);
        if (errors.hasErrors()) {
            return "client/wenda_input";
        }
        Question question = new Question();
        command.toPo(question);
        question.setUserId(getCurrentUser().getId());
        questionService.add(question);
        attributes.addFlashAttribute("msg", String.format("发布成功，请耐心等待审核！<span><a href='%s'>返回</a></span>",
                ConfigResource.getSystemProperty("base_path") + "/question/index"));
        return "redirect:/client/success";
    }

    @RequestMapping(value = "/question/answer", method = RequestMethod.POST)
    @ResponseBody
    public Response questionAnswer(Long id, String content) {
        Response response = new Response();
        User user = getCurrentUser();
        if (user.getId() == -1L) {
            //没有登录
            response.setStatus(-1);
        } else {
            Long answerId;
            Question question = new Question();
            question.setContent(content);
            question.setpId(id);
            question.setStatus(QuestionStatusEnum.显示.getDesc());
            question.setUserId(user.getId());
            questionService.add(question);
            answerId = question.getId();
            question = questionService.getByPrimaryKey(id);
            question.setNum(question.getNum() + 1);
            questionService.update(question);

            response.setData(questionService.getVoById(answerId));
        }
        return response;
    }

    /**
     * 活动
     **/
    @RequestMapping(value = {"/event/index"})
    public String eventIndex(HttpServletRequest request,Model model,Integer page) {
        List<EventVo> vos = new ArrayList<>();
        if(page == null) page = 1;
        if(page > 0){
            int totalSize = eventService.getEventsTotal();
            vos = eventService.getEventsByPage(new PageParam((page - 1) * 6, 6));
            model.addAttribute("pages", NavUtils.build(page, 6, totalSize, request.getRequestURI() + "?page="));
        }

        model.addAttribute("events", vos);
        model.addAttribute("activity_banner_img_1", metaService.getByName("activity_banner_img_1").getType());
        model.addAttribute("activity_banner_img_2", metaService.getByName("activity_banner_img_2").getType());
        model.addAttribute("activity_banner_img_3", metaService.getByName("activity_banner_img_3").getType());
        model.addAttribute("activity_banner_img_4", metaService.getByName("activity_banner_img_4").getType());

        model.addAttribute("activity_banner_url_1", metaService.getByName("activity_banner_url_1").getType());
        model.addAttribute("activity_banner_url_2", metaService.getByName("activity_banner_url_2").getType());
        model.addAttribute("activity_banner_url_3", metaService.getByName("activity_banner_url_3").getType());
        model.addAttribute("activity_banner_url_4", metaService.getByName("activity_banner_url_4").getType());

        LinksParam linksParam = new LinksParam();
        linksParam.setLinkVisible("Y");
        linksParam.setType("活动报道");

        List<Links> as = linksService.getByPage(null,linksParam);
        if(as != null && as.size() > 0)
            model.addAttribute("acs", as);
        return "client/activity_list";
    }

    @RequestMapping(value = {"/event/detail/{id}"})
    public String eventIndex(HttpServletRequest request,Model model, @PathVariable("id") Long id) {
        Events vo = eventService.getByPrimaryKey(id);
        addVisit(vo.getEventId(), VisitTypeEnum.活动.getValue(), request.getRemoteAddr());
        model.addAttribute("e", vo);
        return "client/activity_detail";
    }

    /**
     * 专栏作者发布文章
     **/
    @RequestMapping(value = "/moke/posts/add", method = RequestMethod.GET)
    public String mokePostsAdd(@ModelAttribute EditPostsCommand command) {
        User moke = getCurrentUser();
        if (moke.getId() == -1L) {
            //未登陆
            return "redirect:/login?redirect_url=/moke/posts/add";
        }
        return "client/moke_posts_input";
    }

    @RequestMapping(value = "/moke/posts/add", method = RequestMethod.POST)
    public String mokePostsAdd(Model model, @ModelAttribute EditPostsCommand command, BindingResult errors, RedirectAttributes attributes) {
        if(StringUtils.isEmpty(command.getPostImg()) || StringUtils.isEmpty(command.getPostTitle()) || StringUtils.isEmpty(command.getPostContent())){
            errors.reject("has some error","表单请填写完整！");
        }
        if (errors.hasErrors()) {
            return "client/moke_posts_input";
        }
        Posts posts = new Posts();
        posts.setPostTitle(command.getPostTitle());
        posts.setPostContent(command.getPostContent());
        posts.setPostImg(command.getPostImg());
        posts.setPostAuthor(getCurrentUser().getId());
        posts.setPostType(PostTypeEnum.魔客.getValue());
        posts.setPostStatus(PostsStatusEnum.待审核.getValue());
        posts.setExtra1(getCurrentUser().getUsername());
        postsService.add(posts);
        attributes.addFlashAttribute("msg", String.format("发布成功，请耐心等待审核！<span><a href='%s'>返回</a></span>",
                ConfigResource.getSystemProperty("base_path") + "/profile"));
        return "redirect:/client/success";
    }

    @RequestMapping(value = "/aboutUs")
    public String aboutUs(){
        return "client/about_us";
    }

    /**
     * 搜索内容排列顺序（四大板块，有则显示，无则自动隐藏）
     1、行业大咖信息、数据库产品、公司信息
     2、百科、问答信息（可在侧栏显示）
     3、魔客专栏文章
     4、资讯文章
     * @param model
     * @param keywords
     * @return
     */
    @RequestMapping("/search")
    public String search(Model model,String keywords){
        //大咖
        PeopleParam peopleParam = new PeopleParam();
        peopleParam.setKeywords(keywords);
        peopleParam.setStatus(DataBaseEnum.显示.getValue());
        List<PeopleVo> peopleVos = peopleService.getByPage(null,peopleParam);
        if(peopleVos != null && peopleVos.size() > 0){
            model.addAttribute("peoples",peopleVos);
        }

        //产品
        ProductParam productParam = new ProductParam();
        productParam.setStatus(DataBaseEnum.显示.getValue());
        productParam.setTitle(keywords);
        List<ProductVo> productVos = productService.getByPage(null,productParam);
        if(productVos != null && productVos.size() > 0){
            model.addAttribute("products",productVos);
        }
        //公司
        CompanyParam companyParam = new CompanyParam();
        companyParam.setStatus(DataBaseEnum.显示.getValue());
        companyParam.setKeywords(keywords);
        List<CompanyVo> companyVos = companyService.getByPage(null,companyParam);
        if(companyVos != null && companyVos.size() > 0){
            model.addAttribute("companys",companyVos);
        }

        //百科
        DictParam dictParam = new DictParam();
        dictParam.setKeywords(keywords);
        List<DictVo> dictVos = dictService.getByPage(null,dictParam);
        if (dictVos != null && dictVos.size() > 0) {
            for (DictVo vo : dictVos) {
                if (vo.getContent() != null && vo.getContent().length() > 0) {
                    vo.setContent(HTMLUtil.delHTMLTag(vo.getContent()));
                    if (vo.getContent().length() > 100) {
                        vo.setContent(vo.getContent().substring(0, 100) + "...");
                    }
                }
            }
            model.addAttribute("bakes", dictVos);
        }
        //问答
        QuestionParam questionParam = new QuestionParam();
        questionParam.setKeywords(keywords);
        questionParam.setStatuses(Arrays.asList(QuestionStatusEnum.审核通过.getDesc(),
                QuestionStatusEnum.显示.getDesc(),
                QuestionStatusEnum.推荐.getDesc()));
        questionParam.setPId(0L);
        List<QuestionVo> questionVos = questionService.getByPage(null,questionParam);
        if(questionVos != null && questionVos.size() > 0){
            model.addAttribute("ups",questionVos);
        }
        //专栏文章
        PostsParam param = new PostsParam();
        param.setKeywords("%" + keywords + "%");
        param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue(),
                PostsStatusEnum.审核通过.getValue()));
        param.setType(PostTypeEnum.魔客.getValue());
        List<PostsVo> zhuanlanVos = postsService.getByPage(null,param);
        if (zhuanlanVos != null && zhuanlanVos.size() > 0) {
            for (PostsVo vo : zhuanlanVos) {
                if (vo.getPostContent() != null && vo.getPostContent().length() > 0) {
                    vo.setPostContent(HTMLUtil.delHTMLTag(vo.getPostContent()));
                    if (vo.getPostContent().length() > MAXPREVIEWLENGTH) {
                        vo.setPostContent(vo.getPostContent().substring(0, MAXPREVIEWLENGTH) + "...");
                    }
                }
            }
            model.addAttribute("articles",zhuanlanVos);
        }

        model.addAttribute("ad_url",metaService.getByName("ad_banner_url_1").getType());
        model.addAttribute("ad_img",metaService.getByName("ad_banner_img_1").getType());
        model.addAttribute("keywords",keywords);

        param = new PostsParam();
        param.setType(PostTypeEnum.普通.getValue());
        param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
        param.setOrderClause(" extra_3*1 desc ");
        param.setLimit(5);
        model.addAttribute("vs",postsService.getByPage(null, param));
        return "client/search";
    }

    @RequestMapping(value = "/search/post/page")
    @ResponseBody
    public Response searchPostsPage(HttpServletRequest request,Integer page,String keywords) {
        Response response = new Response();
        //文章
        PostsParam param = new PostsParam();
        param.setKeywords("%" + keywords + "%");
        param.setStatuses(Arrays.asList(PostsStatusEnum.显示.getValue()));
        param.setType(PostTypeEnum.普通.getValue());
        List<PostsVo> vos = postsService.getByPage(new PageParam((page - 1) * 10, 10),param);
        Integer total = postsService.getTotal(param);
        if (vos != null && vos.size() > 0) {
            for (PostsVo vo : vos) {
                if (vo.getPostContent() != null && vo.getPostContent().length() > 0) {
                    vo.setPostContent(HTMLUtil.delHTMLTag(vo.getPostContent()));
                    if (vo.getPostContent().length() > MAXPREVIEWLENGTH) {
                        vo.setPostContent(vo.getPostContent().substring(0, MAXPREVIEWLENGTH) + "...");
                    }
                }
            }
            Map data = new HashMap();
            data.put("list", vos);
            data.put("total", total);
            response.setData(data);
        }
        return response;
    }

    /**
     * 文章评论
     * @param id
     * @param content
     * @return
     */
    @RequestMapping(value = "/post/answer", method = RequestMethod.POST)
    @ResponseBody
    public Response postAnswer(HttpServletRequest request,Long id, String content) {
        Response response = new Response();
        User user = getCurrentUser();
        if (user.getId() == -1L) {
            //没有登录
            response.setStatus(-1);
        } else {
            Comments comments = new Comments();
            comments.setCommentAuthor(user.getId());
            comments.setCommentAuthorIp(request.getRemoteAddr());
            comments.setCommentContent(content);
            comments.setCommentParent(id);
            comments.setCommentPostId(id);
            comments.setCommentApproved(1);//0 为不显示 1 为正常显示
            commentsService.add(comments);

            response.setData(commentsService.getVoById(comments.getId().intValue()));
        }
        return response;
    }

    /**
     * 文章评论  赞！
     * @return
     */
    @RequestMapping("/posts_answer/up")
    @ResponseBody
    public Response upPostAnswer(HttpServletRequest request,HttpServletResponse response,Long id){
        Response res = new Response();
        if(id != null) {
            CommentsVo v = commentsService.getVoById(id.intValue());
            if (v != null) {
                addVisit(id, VisitTypeEnum.评论点赞.getValue(), request.getRemoteAddr());
            }
            CookieUtil.addCookie(response, "bigfa_posts_answer_ding_" + id, v.getLikes() + 1 + "");

            res.setData(v.getLikes() + 1);
        }else{
            res.setData(0);
        }
        return res;
    }

    /**
     * 问答评论  赞！
     * @return
     */
    @RequestMapping("/wenda_answer/up")
    @ResponseBody
    public Response upWendaAnswer(HttpServletRequest request,HttpServletResponse response,Long id){
        QuestionVo v = questionService.getVoById(id);
        if(v != null){
            addVisit(id, VisitTypeEnum.问答点赞.getValue(), request.getRemoteAddr());
            CookieUtil.addCookie(response, "bigfa_wenda_answer_ding_" + id, v.getLikes() + 1 + "");
        }
        Response res = new Response();
        res.setData(v.getLikes() + 1);
        return res;
    }
}
